import time
from functools import wraps

from utils.path_manager import path_manager
from utils.logger import Log as log

log = log()


# 定义重试装饰器，用于处理瞬态错误
def retry(max_attempts=None, delay=None, backoff=None, exceptions=(Exception,)):
    """
    重试装饰器，用于处理瞬态错误
    :param max_attempts: 最大尝试次数，默认使用全局配置
    :param delay: 初始延迟时间（秒），默认使用全局配置
    :param backoff: 延迟时间的增长因子，默认使用全局配置
    :param exceptions: 需要捕获的异常类型
    """

    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            # 使用全局配置作为默认值
            _max_attempts = max_attempts if max_attempts is not None else path_manager.retry_max_attempts
            _delay = delay if delay is not None else path_manager.retry_delay
            _backoff = backoff if backoff is not None else path_manager.retry_backoff

            mtries, mdelay = _max_attempts, _delay
            while mtries > 0:
                try:
                    return func(*args, **kwargs)
                except exceptions as e:
                    mtries -= 1
                    if mtries == 0:
                        raise

                    # 记录重试信息
                    log.warning(
                        f"方法 {func.__name__} 执行失败，将在 {mdelay} 秒后重试，剩余重试次数：{mtries}，异常信息：{str(e)}")

                    # 等待一段时间后重试
                    time.sleep(mdelay)

                    # 增加延迟时间
                    mdelay *= _backoff
            return None

        return wrapper

    return decorator
